import axios, { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import Nprogress from 'nprogress/nprogress';
import { getStorage } from '@/utils/storage';
import { UserInfo } from '@/type/userType';

const request: AxiosInstance = axios.create({
  baseURL: 'http://syt.atguigu.cn/api',
  // baseURL: 'http://syt-api.atguigu.cn/api',
  timeout: 10000,
});

request.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  Nprogress.start();
  const userInfo: UserInfo = getStorage();
  if (userInfo) {
    config.headers.Token = userInfo.token;
  }
  return config;
}, error => {
  return Promise.reject(error);
});

request.interceptors.response.use((response: AxiosResponse) => {
  Nprogress.done();
  if (response.data.code !== 200) return Promise.reject(new Error(response.data.message));
  return response.data;
}, error => {
  Nprogress.done();
  return Promise.reject(error);
});

export default request;
